package my.code.charpter3.part4;

/**
 * 有一个由字符组成的等式：WWWDOT - GOOGLE = DOTCOM，每个字符代表一个0～9之间的数字，
 * WWWDOT、GOOGLE和DOTCOM都是合法的数字，不能以0开头。请找出一组字符和数字的对应关系，
 * 使它们互相替换，并且替换后的数字能够满足等式。
 * @author xuyuji
 *
 */
public class Main {

	public static void main(String[] args) {
		TagCharItem[] charItem = new TagCharItem[9];
		charItem[0] = new TagCharItem('W', -1, true);
		charItem[1] = new TagCharItem('D', -1, true);
		charItem[2] = new TagCharItem('O', -1, false);
		charItem[3] = new TagCharItem('T', -1, false);
		charItem[4] = new TagCharItem('G', -1, true);
		charItem[5] = new TagCharItem('L', -1, false);
		charItem[6] = new TagCharItem('E', -1, false);
		charItem[7] = new TagCharItem('C', -1, false);
		charItem[8] = new TagCharItem('M', -1, false);
		
		TagCharValue[] charValue = new TagCharValue[10];
		for(int i = 0; i < 10; i++){
			charValue[i] = new TagCharValue(false, i);
		}
		
		searchingResult(charItem, charValue, 0);
	}
	
	public static void searchingResult(TagCharItem[] ci, TagCharValue[] cv, int index){
		
		if(index == 9){
			judge(ci);
			return;
		}
		
		for(int i = 0; i < 10; i++){
			TagCharItem ci_now = ci[index];
			TagCharValue cv_now = cv[i];
			if(isValid(ci_now, cv_now)){
				cv_now.setUsed(true);
				ci_now.setValue(cv_now.getValue());
				searchingResult(ci, cv, index + 1);
				cv_now.setUsed(false);
			}
		}
	}
	
	public static void judge(TagCharItem[] ci){
		int WWWDOT = getNum("WWWDOT", ci);
		int GOOGLE = getNum("GOOGLE", ci);
		int DOTCOM = getNum("DOTCOM", ci);
		if(WWWDOT - GOOGLE == DOTCOM){
			System.out.println(String.format("%d - %d = %d", WWWDOT, GOOGLE, DOTCOM));
		}
	}
	
	public static boolean isValid(TagCharItem ci, TagCharValue cv){
		
		if(cv.isUsed()){
			return false;
		}
		
		if(cv.getValue() == 0 && ci.isLeading()){
			return false;
		}
		
		return true;
	}
	
	public static int getNum(String str, TagCharItem[] ci){
		
		int result =  0;
		for(char c : str.toCharArray()){
			for(TagCharItem ci_ : ci){
				if(c == ci_.getC()){
					result = result * 10 + ci_.getValue();
				}
			}
		}
		
		return result;
	}

}